package ICM.client;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;

import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import common.CommandMessage;
import common.SystemEngineer;
import common.TextMessage;
import java.awt.Component;

/**
 * Create Appointment window to appoint staff
 * to appoint supervisors , assessors and system engineers
 *
 */
public class AppointmentUI extends JPanel implements ActionListener,Observer{
	
	JButton btnSave;
	private DefaultTableModel defaultModel = null;
	private Vector newRow = null;
	public ClientUI ui;
	public Client c;
	SystemEngineerUI se;
	private JTable table;
	JComboBox comboBox1 = new JComboBox();
	JComboBox comboBox2 = new JComboBox();
	ArrayList<String[]> stage = new ArrayList<String[]>();
	SystemEngineer[] seng= null;
	private boolean Data = false;
	
	/**
	 * constructor - Builds appointment form
	 * @param c
	 * @param ui
	 */
	public AppointmentUI(Client c, final ClientUI ui)
	{
	   this.c=c;
	   this.ui=ui;
	   c.addObserver(this);
	   setLayout(null);
	   
	   
	   CommandMessage msg = new CommandMessage("SupervisorApp",new Integer[] {Integer.parseInt(se.info[0])});
		
		try {
			c.sendToServer(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
		    Thread.sleep(400);
		} catch(InterruptedException ex) {
		    Thread.currentThread().interrupt();
		}
	   
	   
	   
	   JLabel lbl = new JLabel("This is appointment window for new request");
	   lbl.setBounds(375, 52, 389, 14);
	   add(lbl);
	   
	   JLabel lbl2 = new JLabel("IDRequest: ");
	   lbl2.setBounds(95, 85, 189, 14);
	   add(lbl2);
	   
	   JLabel lblNewLabel = new JLabel(se.info[0]);
	   lblNewLabel.setBounds(192, 85, 46, 14);
	   add(lblNewLabel);
	   
	   btnSave = new JButton("Save",new ImageIcon(AppointmentUI.class.getResource("/client/images/save.png")) );
	   btnSave.addActionListener(this);
	   btnSave.setBounds(192, 368, 108, 38);
	   add(btnSave);
	   
	   JButton btnBack = new JButton("Back"  ,new ImageIcon(AppointmentUI.class.getResource("/client/images/back.png")));
	   /**
	    * Back Button click handler
	    */
	   btnBack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					ui.SetContent(ClientUI.SystemEngineerWindow_Screen);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} 
			}
		});
	   btnBack.setBounds(509, 368, 108, 38);
	   add(btnBack);
	   /**
	    * build new table to appoint supervisor 
	    */
	   table = new JTable();		
		table.setModel(new DefaultTableModel(
				new Object[][] {
				},
				new String[] {
						"Stage", "Duration","Engineer ID"
				}
			));
		 CommandMessage msg1 = new CommandMessage("Get system engineers",null);
			
			try {
				c.sendToServer(msg1);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
			    Thread.sleep(400);
			} catch(InterruptedException ex) {
			    Thread.currentThread().interrupt();
			}
		TableColumn Engineer = table.getColumnModel().getColumn(2);
		 comboBox1 = new JComboBox();
		 comboBox2 = new JComboBox();
		for (int i=0; i<seng.length;i++)
		{
			if (seng[i].getId()!=Integer.parseInt(Client.Login))
			  comboBox1.addItem(Integer.toString(seng[i].getId()));
		}
		for (int i=0; i<seng.length;i++)
		{
			if (seng[i].getId()!=Integer.parseInt(Client.Login))
			  comboBox2.addItem(Integer.toString(seng[i].getId()));
		}
			Engineer.setCellEditor(new DefaultCellEditor(comboBox2));
			Engineer.setCellEditor(new DefaultCellEditor(comboBox1));
			
			defaultModel = (DefaultTableModel) table.getModel();
			JScrollPane pane = new JScrollPane(table); 
			pane.setBounds(41, 124, 867, 226);
			add(pane);
	
			 if (stage!= null)
		        {
		        	newRow = new Vector();      	
		        	for (int j=0;j<stage.size();j++)       		
		        		     defaultModel.addRow(new Object[]{stage.get(j)[0],stage.get(j)[1],stage.get(j)[2]});       		 
		        }
	}
	
	
	@Override
	public void actionPerformed(ActionEvent e) 
	{
		/**
		 * Save button event handler
		 */
		if (e.getSource().equals(btnSave)) 
		{
			//if (table.isEditing())
				//table.getCellEditor().stopCellEditing();
			String newSupervisor1 = comboBox1.getSelectedItem().toString();
			String newSupervisor2 = comboBox2.getSelectedItem().toString();
			String newSupervisor3 = (String)table.getModel().getValueAt(0, 1);
			String newSupervisor4 = (String)table.getModel().getValueAt(1, 1);
			System.out.println("%%"+newSupervisor1+" "+newSupervisor2+" "+newSupervisor3+" "+newSupervisor4);
			/**
			 * Check values
			 */
			if(!isNumeric(newSupervisor3) || !isNumeric(newSupervisor4)){
				ClientUI.ShowMessageBox("Error", "Wrong values", JOptionPane.ERROR_MESSAGE);
			}
			/**
			 * If values are correct
			 */
			else
			{
				String status =se.info[2];
				System.out.println(status);
		   CommandMessage msg2 = new CommandMessage("Change data",new String[] {se.info[0],newSupervisor1,newSupervisor2,newSupervisor3,newSupervisor4,status});
		   try {
				c.sendToServer(msg2);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
			    Thread.sleep(400);
			} catch(InterruptedException ex) {
			    Thread.currentThread().interrupt();
			}
		}
			
		}
	}
	/**
	 * Check if values are numbers
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str)
	{
	    for (char c : str.toCharArray())	    
	        if (!Character.isDigit(c)) return false;	    
	    return true;
	}


	/**
	 * Handle massage from Observable class in our case Client
	 */
	public void update(Observable arg0, Object arg1) 
	{
		String msg = "";
		String msg1 = "";
		if (arg1 instanceof TextMessage)
			msg = ((TextMessage)arg1).ToDebugMessage();
		else if (arg1 instanceof CommandMessage) {
			CommandMessage ms=(CommandMessage)arg1;
			//Searching for user active requests 
			if(ms.getCommand().equals("Appointment stage"))	
			{
				
				stage = (ArrayList<String[]>) ms.getParams()[1];
			}
			else if (ms.getCommand().equals("All system engineers")){
				seng = (SystemEngineer[]) ms.getParams()[1];
			}
			else if (ms.getCommand().equals("Data")){
				Data = Boolean.parseBoolean(ms.getParams()[1].toString());
			}
		}
		else
			msg = arg1.toString();
	}	
}
